//
//  BusiProxyHandler.swift
//  OneDay
//
//  Created by xicheng on 16/11/15.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit
import SwiftyJSON


class BusiProxyHandler<MODEL:BaseModel>: NSObject,TXNetworkResponce {

  
  var successBlock:((MODEL)->Void)? = nil
  
  var errorBlock:((MODEL?,NetworkError)->Void)? = nil

  var onfinishBlock:((NetworkTask)->Bool)? = nil

  
  init(success:((MODEL)->Void)?,error:((MODEL?,NetworkError)->Void)?,onfinish:((NetworkTask)->Bool)?) {
    super.init()
    self.successBlock = success
    self.errorBlock = error
    self.onfinishBlock = onfinish

  }
  
  
  func handler(response: ResponseProxy,AndTask task:NetworkTask) {
    
    if let result = response.response {
      TXLogDebug("网络接口调用：responce:\(result)")
      if let resultModel:MODEL = MODEL.model(withJSON: result) {
      
        if  resultModel.code == CodeStatus.CODE_SUCCESS {
          if let success = self.successBlock {
            //MARK: header
            success(resultModel)
          }
        }else {
          if let error = self.errorBlock {
            error(resultModel, NetworkError.code(resultModel.code))
          }
        }
        
      
      }else {
        // MARK: json无法解析成功
        if let error = self.errorBlock {
          error(nil, NetworkError.jsonParse)
        }
      }
    }else {
      if let error = self.errorBlock {
        error(nil,NetworkError.nullData)
      }
    }
    
  }
  
  func handler(error: Error, AndTask task: NetworkTask) {
    // MARK: error 处理
    self.errorBlock?(nil,NetworkError.networkError(error))
  }
  
  func onfinish(task: NetworkTask) -> Bool {
    
    if let block = self.onfinishBlock {
      return block(task)
    }
    return true
  }
  
  
}
